package com.rainbow.redis.plus.core.utils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class JsonUtils {
	private static final ObjectMapper objectMapper = new ObjectMapper();
	private static final String STANDARD_FORMAT="yyyy-MM-dd HH:mm:ss";
	
	static {
		//对象的所有字段全部列入
		objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
		//取消默认转化timestamps格式
		objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
		//忽略空bean转json的错误
		objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
		//所有日期格式统一格式：yyyy-MM-dd HH:mm:ss
		objectMapper.setDateFormat(new SimpleDateFormat(STANDARD_FORMAT));
		//忽略在json字符串中存在，但是在java对象中不存在对应属性的情况，防止错误
		objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Map<String,Object> json2Map(String json) throws IOException {
        Map map = (Map) objectMapper.readValue(json,Map.class);
        return map;
    }
 
    public static String object2Json(Object object) throws IOException {
        return objectMapper.writeValueAsString(object);
    }
 
    public static <T> T json2Object(String json,Class<T> clazz) throws IOException {
        return objectMapper.readValue(json,clazz);
    }
 
    @SuppressWarnings("rawtypes")
	public static List<?> json2List(String json,TypeReference<?> typeRef) throws IOException {
        List list = (List) objectMapper.readValue(json,typeRef);
        return list;
    }
}
